package vn.conghuy.talkwithme.data.livescore;

import java.io.IOException;
import java.util.ArrayList;

import org.jsoup.Jsoup;

public class LivescoreWinLoseTipMgr {
	
	ArrayList<LivescoreWinLoseTip> tips;
	
	private static final String BEGIN_TIP = "<td style=\"WIDTH: 15%\" valign=\"top\" align=\"center\">";  
	private static final String BEGIN_RATIO = "<td align=\"center\" style=\"FONT-WEIGHT: bold\">";
	public LivescoreWinLoseTipMgr() {
		tips = new ArrayList<LivescoreWinLoseTip>();
	}
	
	public void update(){
		String html;
		try {
			html = Jsoup.connect("http://soikeo.com/tip-bong-da.SoiKeo").userAgent("Mozilla/6.0 (Windows NT 6.2; WOW64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1").get().html();
			String lines[] = html.split("\n");
			for(int i = 0; i < lines.length;){
				String line = lines[i].trim();
				if(line.startsWith(BEGIN_TIP)){
					line = lines[i + 2].trim();
					String ratio = line.substring(BEGIN_RATIO.length());
					ratio = ratio.replace("</td>", "");
					if(ratio.contains(":")){
						LivescoreWinLoseTip tip = new LivescoreWinLoseTip();
						tip.ratio = ratio;
						
						line = lines[i + 1].trim();
						String homeAway = line.replaceAll("<td align=\"center\"><b>|</b></td>", "");
						String[] homeAwayArray = homeAway.split(" - ");
						tip.home = homeAwayArray[0];
						tip.away = homeAwayArray[1];
						
						line = lines[i+4].trim();
						String choose = line.substring(BEGIN_RATIO.length());
						choose = choose.replace("</td>", "");
						tip.choose = choose;
						
						tips.add(tip);
						
					}
					i+=5;
				}
				else i++;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String toHtmlString(){
		StringBuilder strBuilder = new StringBuilder();
		for(LivescoreWinLoseTip tip : tips){
			strBuilder.append("<b>=></b> ").append(tip.home).append(" <b>").append(tip.ratio).append("</b> ").append(tip.away)
			.append(", choose <b>").append(tip.choose).append("</b>\n\n");
		}
		String result = strBuilder.toString();
		if(result.equals("") == false) return result;
		return null;
	}
}
